package com.ubb.dbms.core.fileManagers.indexFileManager;

import java.io.File;

import com.ubb.dbms.core.checker.DomainObjectChecker;
import com.ubb.dbms.core.fileManagers.dataFileManager.DataFileManager;
import com.ubb.dbms.core.fileManagers.indexFileManager.bPlusTree.BPlusTree;
import com.ubb.dbms.core.fileManagers.indexFileManager.bPlusTree.Node;
import com.ubb.dbms.domain.xml.IndexFile;
import com.ubb.dbms.domain.xml.Table;

public class IndexFileManagerImpl implements IndexFileManager {

	@Override
	public void createFileForIndex(IndexFile indexFile, Table table, String usesDatabase) {
		// building the partial path for index and rows state index files
		String indexFileFolder = getIndexFileFolder(usesDatabase, table.getTableName());
		String rsIndexFilePath = getRsIndexFilePath(indexFileFolder, indexFile);
		// creates the files for the index
		new IndexFileIO(indexFilePath, rsIndexFilePath, HEADER_LENGTH, 0);
	}

	@Override
	public void insertKey(Object key, int dataFileRowNr, String usesDatabase, Table table, IndexFile indexFile) {
		int indexRowLength = getIndexRowLength();
		String indexFileFolder = getIndexFileFolder(usesDatabase, table.getTableName());
		String rsIndexFilePath = getRsIndexFilePath(indexFileFolder, indexFile);
		IndexFileIO indexFileIO = new IndexFileIO(indexFilePath, rsIndexFilePath, HEADER_LENGTH, indexRowLength);
		int rootNodeRowNr = indexFileIO.readFileHeader();
		BPlusTree bPlusTree;
		if (rootNodeRowNr == 0) {
			bPlusTree = new BPlusTree(indexFileIO);
		} else {
			Node rootNode = indexFileIO.readRow(rootNodeRowNr);
			bPlusTree = new BPlusTree(rootNode, indexFileIO);
		}
		bPlusTree.add(Integer.parseInt(key.toString()), dataFileRowNr);
	}

	public static int getIndexRowLength() {
		return 2 + (2 * T - 1) * DomainObjectChecker.DEFAULT_INT_LENGTH + 2 * T * DomainObjectChecker.DEFAULT_INT_LENGTH;
	}

	public static String getIndexFileFolder(String usesDatabase, String tableName) {
		return DataFileManager.DATABASES_FOLDER_NAME + usesDatabase + File.separator + tableName + File.separator + INDEXES_FOLDER_NAME;
	}

	public static String getRsIndexFilePath(String indexFileFolder, IndexFile indexFile) {
		return indexFileFolder + indexFile.getIndexName() + ROWS_STATES_INDEX_FILES_EXTENSION;
	}
}
